package com.example.project.mapper;

import com.example.project.entity.IssueComment;
import com.example.project.entity.IssueCommentAttachment;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

/**
 * 需求评论Mapper接口
 */
@Mapper
public interface IssueCommentMapper {

    /**
     * 插入评论
     */
    @Insert("INSERT INTO t_issue_comment (issue_id, parent_id, author_id, content, create_time, update_time) " +
            "VALUES (#{issueId}, #{parentId}, #{authorId}, #{content}, NOW(), NOW())")
    int insert(IssueComment comment);

    /**
     * 根据ID更新评论
     */
    @Update("UPDATE t_issue_comment SET issue_id = #{issueId}, parent_id = #{parentId}, author_id = #{authorId}, " +
            "content = #{content}, update_time = NOW() WHERE id = #{id}")
    int updateById(IssueComment comment);

    /**
     * 根据ID删除评论
     */
    @Delete("DELETE FROM t_issue_comment WHERE id = #{id}")
    int deleteById(Long id);

    /**
     * 根据ID查询评论
     */
    @Select("SELECT * FROM t_issue_comment WHERE id = #{id}")
    IssueComment selectById(Long id);

    /**
     * 根据需求ID获取评论列表（按创建时间升序）
     */
    @Select("SELECT * FROM t_issue_comment WHERE issue_id = #{issueId} ORDER BY create_time ASC")
    List<IssueComment> getCommentsByIssueId(@Param("issueId") Long issueId);

    /**
     * 根据需求ID获取评论列表（按创建时间降序）
     */
    @Select("SELECT * FROM t_issue_comment WHERE issue_id = #{issueId} ORDER BY create_time DESC")
    List<IssueComment> getLatestCommentsByIssueId(@Param("issueId") Long issueId);

    /**
     * 获取根评论（没有父评论的评论）
     */
    @Select("SELECT * FROM t_issue_comment WHERE issue_id = #{issueId} AND parent_id IS NULL ORDER BY create_time ASC")
    List<IssueComment> getRootCommentsByIssueId(@Param("issueId") Long issueId);

    /**
     * 根据父评论ID获取回复列表
     */
    @Select("SELECT * FROM t_issue_comment WHERE parent_id = #{parentId} ORDER BY create_time ASC")
    List<IssueComment> getRepliesByParentId(@Param("parentId") Long parentId);

    /**
     * 根据用户ID获取评论列表
     */
    @Select("SELECT * FROM t_issue_comment WHERE author_id = #{authorId} ORDER BY create_time DESC")
    List<IssueComment> getCommentsByAuthorId(@Param("authorId") Long authorId);

    /**
     * 根据时间范围获取评论列表
     */
    @Select("SELECT * FROM t_issue_comment WHERE create_time >= #{startTime} AND create_time <= #{endTime}")
    List<IssueComment> getCommentsByTimeRange(@Param("startTime") String startTime, @Param("endTime") String endTime);

    /**
     * 获取用户的评论数量
     */
    @Select("SELECT COUNT(*) FROM t_issue_comment WHERE author_id = #{authorId}")
    Integer countCommentsByAuthorId(@Param("authorId") Long authorId);

    /**
     * 获取需求的评论数量
     */
    @Select("SELECT COUNT(*) FROM t_issue_comment WHERE issue_id = #{issueId}")
    Integer countCommentsByIssueId(@Param("issueId") Long issueId);

    /**
     * 根据多个条件查询评论
     */
    @Select("<script>" +
            "SELECT c.*, u.user_name as author_name, u.avatar as author_avatar " +
            "FROM t_issue_comment c " +
            "LEFT JOIN t_user u ON c.author_id = u.user_id " +
            "<where>" +
            "<if test='issueId != null'>AND c.issue_id = #{issueId} </if>" +
            "<if test='authorId != null'>AND c.author_id = #{authorId} </if>" +
            "<if test='parentId != null'>AND c.parent_id = #{parentId} </if>" +
            "<if test='parentId == null and parentIdCheck == true'>AND c.parent_id IS NULL </if>" +
            "<if test='content != null and content != \"\"'>AND c.content LIKE CONCAT('%', #{content}, '%') </if>" +
            "<if test='deleted != null'>AND c.deleted = #{deleted} </if>" +
            "<if test='startTime != null and startTime != \"\"'>AND c.create_time &gt;= #{startTime} </if>" +
            "<if test='endTime != null and endTime != \"\"'>AND c.create_time &lt;= #{endTime} </if>" +
            "<if test='projectId != null'>AND c.issue_id IN (SELECT id FROM t_issue WHERE project_id = #{projectId}) </if>" +
            "<if test='hasAttachments != null'>AND <choose>" +
            "<when test='hasAttachments == true'>" +
            "EXISTS (SELECT 1 FROM t_issue_comment_attachment a WHERE a.comment_id = c.id) " +
            "</when>" +
            "<when test='hasAttachments == false'>" +
            "NOT EXISTS (SELECT 1 FROM t_issue_comment_attachment a WHERE a.comment_id = c.id) " +
            "</when>" +
            "</choose>" +
            "</if>" +
            "</where>" +
            "<choose>" +
            "<when test='orderBy != null and orderBy != \"\"'>ORDER BY ${orderBy} </when>" +
            "<otherwise>ORDER BY c.create_time DESC </otherwise>" +
            "</choose>" +
            "<if test='limit != null and limit > 0'>LIMIT #{limit} </if>" +
            "<if test='offset != null and offset > 0'>OFFSET #{offset} </if>" +
            "</script>")
    List<IssueComment> getCommentsByConditions(Map<String, Object> conditions);

    /**
     * 更新评论状态（如删除标记）
     */
    @Update("UPDATE t_issue_comment SET deleted = #{deleted} WHERE id = #{commentId}")
    int updateCommentStatus(@Param("commentId") Long commentId, @Param("deleted") Boolean deleted);

    /**
     * 获取最近评论
     */
    @Select("SELECT * FROM t_issue_comment ORDER BY create_time DESC LIMIT #{limit}")
    List<IssueComment> getLatestComments(@Param("limit") Integer limit);

    /**
     * 获取项目的评论统计
     */
    @Select("SELECT i.project_id, COUNT(c.id) as comment_count " +
            "FROM t_issue_comment c JOIN t_issue i ON c.issue_id = i.id " +
            "WHERE i.project_id = #{projectId} GROUP BY i.project_id")
    Map<String, Object> getCommentStatsByProjectId(@Param("projectId") Long projectId);

    /**
     * 获取未读评论数量
     */
    @Select("SELECT COUNT(*) FROM t_issue_comment c " +
            "WHERE c.issue_id = #{issueId} AND c.author_id != #{userId} " +
            "AND c.create_time > (SELECT last_read_time FROM t_issue_read_status WHERE issue_id = #{issueId} AND user_id = #{userId})")
    Integer getUnreadCommentCount(@Param("issueId") Long issueId, @Param("userId") Long userId);

    /**
     * 根据评论ID获取附件列表
     */
    @Select("SELECT * FROM t_issue_comment_attachment WHERE comment_id = #{commentId}")
    List<IssueCommentAttachment> getAttachmentsByCommentId(@Param("commentId") Long commentId);

    /**
     * 插入评论附件
     */
    @Insert("INSERT INTO t_issue_comment_attachment (comment_id, filename, file_path, file_size, content_type, create_time) " +
            "VALUES (#{commentId}, #{filename}, #{filePath}, #{fileSize}, #{contentType}, NOW())")
    int insertAttachment(@Param("commentId") Long commentId, @Param("filename") String filename, @Param("filePath") String filePath, 
                         @Param("fileSize") Long fileSize, @Param("contentType") String contentType);

    /**
     * 删除评论的所有附件
     */
    @Delete("DELETE FROM t_issue_comment_attachment WHERE comment_id = #{commentId}")
    int deleteAttachmentsByCommentId(@Param("commentId") Long commentId);
}